package com.ruoyi.common.redis.handler;

import org.redisson.api.NameMapper;

/**
 * redis缓存key前缀处理
 *
 * @author ye
 * @date 2022/7/14 17:44
 * @since 4.3.0
 */
public class KeyPrefixHandler implements NameMapper {

    private final String keyPrefix;

    public KeyPrefixHandler(String keyPrefix) {
        //前缀为空 则返回空前缀
        this.keyPrefix = isBlank(keyPrefix) ? "" : keyPrefix + ":";
    }

    /**
     * 增加前缀
     */
    @Override
    public String map(String name) {
        if (isBlank(name)) {
            return null;
        }
        if (isNotBlank(keyPrefix) && !name.startsWith(keyPrefix)) {
            return keyPrefix + name;
        }
        return name;
    }

    /**
     * 去除前缀
     */
    @Override
    public String unmap(String name) {
        if (isBlank(name)) {
            return null;
        }
        if (isNotBlank(keyPrefix) && name.startsWith(keyPrefix)) {
            return name.substring(keyPrefix.length());
        }
        return name;
    }

    private boolean isBlank(String string) {
        if (isEmpty(string)) {
            return true;
        }
        for (int i = 0; i < string.length(); i++) {
            if (!Character.isWhitespace(string.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * Check if the String has any non-whitespace character.
     * @param string String to check
     * @return {@code true} if the String has any non-whitespace character
     */
    private boolean isNotBlank(String string) {
        return !isBlank(string);
    }

    /**
     * Check if the String is null or empty.
     * @param string String to check
     * @return {@code true} if the String is null or empty
     */
    private boolean isEmpty(String string) {
        return string == null || string.isEmpty();
    }


}
